<template>
	<cl-page>
		<view class="buy-gift-page">
			<!-- 自定义导航栏 -->
			<cl-topbar title="买赠活动" background-color="#9c27b0">
				<template #append>
					<view class="activity-timer" v-if="activityTime">
						<cl-icon name="cl-icon-time" color="#fff" :size="32" />
						<text>{{ activityTime }}</text>
					</view>
				</template>
			</cl-topbar>

			<!-- 活动横幅 -->
			<view class="activity-banner">
				<view class="banner-bg">
					<view class="banner-content">
						<view class="banner-main">
							<cl-icon name="cl-icon-present" :size="80" color="#fff" />
							<view class="banner-text">
								<view class="banner-title">买就送好礼</view>
								<view class="banner-subtitle">购买指定商品，免费赠送精选好礼</view>
							</view>
						</view>
						<view class="banner-rules" @tap="showRules">
							<text>活动规则</text>
							<cl-icon name="cl-icon-arrow-right" :size="28" color="#fff" />
						</view>
					</view>
				</view>
			</view>

			<!-- 分类标签 -->
			<view class="category-tabs">
				<scroll-view scroll-x class="tabs-scroll">
					<view class="tabs-list">
						<view
							class="tab-item"
							:class="{ active: currentCategory === cat.value }"
							v-for="cat in categories"
							:key="cat.value"
							@tap="selectCategory(cat.value)"
						>
							<view class="tab-icon" v-if="cat.icon">
								<cl-icon :name="cat.icon" :size="36" />
							</view>
							<text>{{ cat.label }}</text>
							<view class="tab-badge" v-if="cat.count">{{ cat.count }}</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 买赠商品列表 -->
			<view class="gift-list">
				<view
					class="gift-card"
					v-for="item in giftList"
					:key="item.id"
					@tap="toDetail(item.id)"
				>
					<!-- 活动标签 -->
					<view class="activity-badge">
						<text>买{{ item.buyCount }}赠{{ item.giftCount }}</text>
					</view>

					<!-- 商品主体 -->
					<view class="gift-main">
						<!-- 主商品 -->
						<view class="main-product">
							<view class="product-image">
								<image :src="item.mainProduct.imgUrl || '/static/icon/no-image.png'" mode="aspectFill" />
								<view class="buy-tag">购买</view>
							</view>
							<view class="product-info">
								<view class="product-name">{{ item.mainProduct.name }}</view>
								<view class="product-spec">{{ item.mainProduct.spec }}</view>
								<view class="product-price">
									<text class="symbol">¥</text>
									<text class="value">{{ item.mainProduct.price }}</text>
								</view>
							</view>
						</view>

						<!-- 赠品 -->
						<view class="gift-products">
							<view class="gift-label">
								<cl-icon name="cl-icon-gift" :size="32" color="#9c27b0" />
								<text>赠品</text>
							</view>
							<view class="gift-items">
								<view
									class="gift-item"
									v-for="(gift, idx) in item.giftProducts"
									:key="idx"
								>
									<view class="gift-image">
										<image :src="gift.imgUrl || '/static/icon/no-image.png'" mode="aspectFill" />
										<view class="gift-quantity" v-if="gift.quantity > 1">
											x{{ gift.quantity }}
										</view>
									</view>
									<view class="gift-info">
										<view class="gift-name">{{ gift.name }}</view>
										<view class="gift-spec">{{ gift.spec }}</view>
										<view class="gift-value">价值 ¥{{ gift.value }}</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 活动信息 -->
					<view class="activity-info">
						<view class="info-item">
							<cl-icon name="cl-icon-box" :size="28" color="#666" />
							<text>库存: {{ item.stock }}份</text>
						</view>
						<view class="info-item">
							<cl-icon name="cl-icon-time" :size="28" color="#666" />
							<text>{{ formatEndTime(item.endTime) }}</text>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="card-actions">
						<view class="total-value">
							<text class="label">总价值</text>
							<text class="value">¥{{ item.totalValue }}</text>
						</view>
						<cl-button
							type="primary"
							size="medium"
							round
							@tap.stop="addToCart(item)"
							:disabled="item.stock <= 0"
						>
							<cl-icon name="cl-icon-cart" />
							<text>{{ item.stock > 0 ? '立即购买' : '已售罄' }}</text>
						</cl-button>
					</view>

					<!-- 进度条 -->
					<view class="progress-bar" v-if="item.stock > 0">
						<view class="progress-info">
							<text>已售 {{ item.sold }}%</text>
							<text>剩余 {{ item.stock }}份</text>
						</view>
						<view class="progress-track">
							<view class="progress-fill" :style="{ width: item.sold + '%' }"></view>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<cl-empty
				v-if="isEmpty"
				description="暂无买赠活动"
				image="/static/icon/empty-gift.png"
			>
				<cl-button type="primary" size="small" round @tap="toHome">去首页看看</cl-button>
			</cl-empty>

			<!-- 加载更多 -->
			<cl-loadmore
				v-if="!isEmpty"
				:loading="loading"
				:finished="finished"
				@loadmore="loadMore"
			/>

			<!-- 规则弹窗 -->
			<cl-popup v-model="rulesVisible" direction="bottom" :size="800">
				<view class="rules-popup">
					<view class="popup-header">
						<text class="title">买赠活动规则</text>
						<cl-icon name="cl-icon-close" :size="40" @tap="rulesVisible = false" />
					</view>
					<scroll-view scroll-y class="popup-content">
						<view class="rule-section">
							<view class="rule-title">活动说明</view>
							<view class="rule-list">
								<view class="rule-item">
									<text class="num">1</text>
									<text class="text">购买指定商品达到规定数量，即可获得相应赠品。</text>
								</view>
								<view class="rule-item">
									<text class="num">2</text>
									<text class="text">赠品数量有限，先到先得，送完即止。</text>
								</view>
								<view class="rule-item">
									<text class="num">3</text>
									<text class="text">同一订单同一商品仅可享受一次买赠优惠。</text>
								</view>
							</view>
						</view>
						<view class="rule-section">
							<view class="rule-title">注意事项</view>
							<view class="rule-list">
								<view class="rule-item">
									<text class="num">•</text>
									<text class="text">赠品不支持单独退换货。</text>
								</view>
								<view class="rule-item">
									<text class="num">•</text>
									<text class="text">如主商品退货，赠品需一并退回。</text>
								</view>
								<view class="rule-item">
									<text class="num">•</text>
									<text class="text">活动最终解释权归平台所有。</text>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</cl-popup>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { onReady, onReachBottom } from "@dcloudio/uni-app";
import { useCool, usePager } from "/@/cool";
import { useShoppingCart } from "/@/hooks/shopping-cart";

const { service, router } = useCool();
const { onRefresh, onData, isEmpty, loading, finished } = usePager();
const { addGoods } = useShoppingCart();

// 活动倒计时
const activityTime = ref("");
let timer: any = null;

// 分类选项
const categories = [
	{ label: "全部", value: "", icon: "", count: 0 },
	{ label: "感冒药", value: "cold", icon: "cl-icon-yao", count: 12 },
	{ label: "营养保健", value: "nutrition", icon: "cl-icon-vitamin", count: 8 },
	{ label: "家庭常备", value: "family", icon: "cl-icon-home", count: 15 },
	{ label: "母婴用品", value: "baby", icon: "cl-icon-baby", count: 6 },
];

// 当前分类
const currentCategory = ref("");

// 买赠列表
const giftList = ref<any[]>([]);

// 规则弹窗
const rulesVisible = ref(false);

// 获取买赠列表
function refresh(params?: any) {
	const { data, next } = onRefresh(params);

	onData((list) => {
		// 模拟买赠数据
		const mockList = list.map((item: any, index: number) => ({
			id: item.id || index + 1,
			buyCount: Math.floor(Math.random() * 3) + 1,
			giftCount: 1,
			mainProduct: {
				name: "999感冒灵颗粒",
				spec: "10g*20袋",
				imgUrl: "/static/icon/no-image.png",
				price: "25.90",
			},
			giftProducts: [
				{
					name: "维生素C片",
					spec: "100mg*30片",
					imgUrl: "/static/icon/no-image.png",
					value: "15.00",
					quantity: 1,
				},
				{
					name: "医用口罩",
					spec: "10只装",
					imgUrl: "/static/icon/no-image.png",
					value: "9.90",
					quantity: 1,
				},
			],
			totalValue: "50.80",
			stock: Math.floor(Math.random() * 100) + 1,
			sold: Math.floor(Math.random() * 80) + 20,
			endTime: new Date(Date.now() + Math.random() * 7 * 24 * 60 * 60 * 1000),
		}));

		if (data.page == 1) {
			giftList.value = mockList;
		} else {
			giftList.value.push(...mockList);
		}
	});

	// 模拟API调用
	return next(
		new Promise((resolve) => {
			setTimeout(() => {
				resolve({
					list: Array(10).fill({}).map((_, i) => ({ id: Date.now() + i })),
					pagination: { total: 30 },
				});
			}, 1000);
		})
	);
}

// 选择分类
function selectCategory(value: string) {
	currentCategory.value = value;
	refresh({ page: 1, category: value });
}

// 显示规则
function showRules() {
	rulesVisible.value = true;
}

// 格式化结束时间
function formatEndTime(endTime: Date) {
	const now = new Date();
	const diff = endTime.getTime() - now.getTime();
	const days = Math.floor(diff / (1000 * 60 * 60 * 24));
	
	if (days > 0) {
		return `还剩${days}天`;
	} else {
		const hours = Math.floor(diff / (1000 * 60 * 60));
		return `还剩${hours}小时`;
	}
}

// 更新倒计时
function updateCountdown() {
	const endTime = new Date("2024-12-31 23:59:59");
	const now = new Date();
	const diff = endTime.getTime() - now.getTime();
	
	if (diff <= 0) {
		activityTime.value = "活动已结束";
		return;
	}
	
	const days = Math.floor(diff / (1000 * 60 * 60 * 24));
	const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
	const seconds = Math.floor((diff % (1000 * 60)) / 1000);
	
	activityTime.value = `${days}天${hours}时${minutes}分${seconds}秒`;
}

// 跳转详情
function toDetail(id: number) {
	router.push({
		path: "/pages/goods/detail",
		query: { id },
	});
}

// 加入购物车
async function addToCart(item: any) {
	try {
		// 这里应该调用专门的买赠加入购物车接口
		uni.showToast({
			title: "买赠功能开发中",
			icon: "none",
		});
	} catch (error) {
		console.error("加入购物车失败:", error);
	}
}

// 跳转首页
function toHome() {
	router.push("/pages/index/home");
}

// 加载更多
function loadMore() {
	refresh({ page: giftList.value.length / 10 + 1 });
}

onMounted(() => {
	updateCountdown();
	timer = setInterval(updateCountdown, 1000);
});

onUnmounted(() => {
	if (timer) {
		clearInterval(timer);
	}
});

onReady(() => {
	refresh();
});

onReachBottom(() => {
	if (!loading.value && !finished.value) {
		loadMore();
	}
});
</script>

<style lang="scss" scoped>
.buy-gift-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

// 活动计时器
.activity-timer {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 20rpx;
	background-color: rgba(255, 255, 255, 0.2);
	border-radius: 30rpx;
	font-size: 24rpx;
	color: #fff;
}

// 活动横幅
.activity-banner {
	.banner-bg {
		background: linear-gradient(135deg, #9c27b0, #7b1fa2);
		padding: 40rpx;
		position: relative;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			top: -50%;
			right: -20%;
			width: 300rpx;
			height: 300rpx;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 70%);
			border-radius: 50%;
		}

		&::after {
			content: "";
			position: absolute;
			bottom: -30%;
			left: -10%;
			width: 200rpx;
			height: 200rpx;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.15) 0%, transparent 70%);
			border-radius: 50%;
		}
	}

	.banner-content {
		position: relative;
		z-index: 1;
	}

	.banner-main {
		display: flex;
		align-items: center;
		gap: 24rpx;
		margin-bottom: 24rpx;
	}

	.banner-text {
		flex: 1;

		.banner-title {
			font-size: 40rpx;
			font-weight: 600;
			color: #fff;
			margin-bottom: 12rpx;
		}

		.banner-subtitle {
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.9);
		}
	}

	.banner-rules {
		display: flex;
		align-items: center;
		gap: 8rpx;
		color: #fff;
		font-size: 26rpx;
		opacity: 0.9;

		&:active {
			opacity: 0.7;
		}
	}
}

// 分类标签
.category-tabs {
	background-color: #fff;
	padding: 20rpx 0;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	.tabs-scroll {
		white-space: nowrap;
	}

	.tabs-list {
		display: inline-flex;
		padding: 0 20rpx;
		gap: 24rpx;
	}

	.tab-item {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		padding: 16rpx 24rpx;
		border-radius: 16rpx;
		transition: all 0.3s;
		position: relative;

		.tab-icon {
			width: 60rpx;
			height: 60rpx;
			background: linear-gradient(135deg, #f5f5f5, #e8e8e8);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s;
		}

		text {
			font-size: 26rpx;
			color: #666;
			transition: all 0.3s;
		}

		.tab-badge {
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			min-width: 32rpx;
			height: 32rpx;
			background-color: #ff4444;
			color: #fff;
			font-size: 20rpx;
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 8rpx;
		}

		&.active {
			background-color: rgba(156, 39, 176, 0.1);

			.tab-icon {
				background: linear-gradient(135deg, #9c27b0, #7b1fa2);
				color: #fff;
			}

			text {
				color: #9c27b0;
				font-weight: 600;
			}
		}

		&:active {
			transform: scale(0.95);
		}
	}
}

// 买赠列表
.gift-list {
	padding: 0 20rpx 20rpx;
}

.gift-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 32rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	position: relative;
	overflow: hidden;
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
	}

	// 活动标签
	.activity-badge {
		position: absolute;
		top: 0;
		right: 40rpx;
		background: linear-gradient(135deg, #ff6b6b, #ff5252);
		color: #fff;
		padding: 12rpx 24rpx 20rpx;
		border-radius: 0 0 20rpx 20rpx;
		font-size: 26rpx;
		font-weight: 600;
		box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.3);
	}

	// 商品主体
	.gift-main {
		margin-bottom: 24rpx;
	}

	.main-product {
		display: flex;
		gap: 20rpx;
		padding-bottom: 24rpx;
		border-bottom: 2rpx dashed #eee;
		margin-bottom: 24rpx;

		.product-image {
			position: relative;
			width: 160rpx;
			height: 160rpx;
			border-radius: 16rpx;
			overflow: hidden;
			background-color: #f8f9fa;

			image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.buy-tag {
				position: absolute;
				top: 0;
				left: 0;
				background-color: #9c27b0;
				color: #fff;
				padding: 4rpx 16rpx;
				border-radius: 0 0 16rpx 0;
				font-size: 22rpx;
			}
		}

		.product-info {
			flex: 1;

			.product-name {
				font-size: 30rpx;
				font-weight: 500;
				color: #333;
				margin-bottom: 12rpx;
				line-height: 1.4;
			}

			.product-spec {
				font-size: 26rpx;
				color: #999;
				margin-bottom: 16rpx;
			}

			.product-price {
				display: flex;
				align-items: baseline;
				color: #ff4444;

				.symbol {
					font-size: 28rpx;
					font-weight: 600;
				}

				.value {
					font-size: 40rpx;
					font-weight: 700;
					margin-left: 4rpx;
				}
			}
		}
	}

	// 赠品区域
	.gift-products {
		.gift-label {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 28rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 16rpx;
		}

		.gift-items {
			display: flex;
			flex-wrap: wrap;
			gap: 16rpx;
		}

		.gift-item {
			display: flex;
			align-items: center;
			gap: 12rpx;
			padding: 12rpx;
			background-color: #f8f9fa;
			border-radius: 12rpx;
			flex: 1;
			min-width: 280rpx;

			.gift-image {
				position: relative;
				width: 80rpx;
				height: 80rpx;
				border-radius: 8rpx;
				overflow: hidden;
				background-color: #fff;

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}

				.gift-quantity {
					position: absolute;
					bottom: 0;
					right: 0;
					background-color: rgba(0, 0, 0, 0.6);
					color: #fff;
					padding: 2rpx 8rpx;
					border-radius: 8rpx 0 8rpx 0;
					font-size: 20rpx;
				}
			}

			.gift-info {
				flex: 1;

				.gift-name {
					font-size: 26rpx;
					color: #333;
					margin-bottom: 4rpx;
				}

				.gift-spec {
					font-size: 22rpx;
					color: #999;
					margin-bottom: 4rpx;
				}

				.gift-value {
					font-size: 24rpx;
					color: #9c27b0;
					font-weight: 500;
				}
			}
		}
	}

	// 活动信息
	.activity-info {
		display: flex;
		gap: 32rpx;
		padding: 20rpx 0;
		border-top: 2rpx solid #f5f5f5;
		border-bottom: 2rpx solid #f5f5f5;
		margin: 24rpx 0;

		.info-item {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 26rpx;
			color: #666;
		}
	}

	// 操作按钮
	.card-actions {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.total-value {
			display: flex;
			flex-direction: column;
			gap: 4rpx;

			.label {
				font-size: 24rpx;
				color: #999;
			}

			.value {
				font-size: 32rpx;
				color: #ff4444;
				font-weight: 600;
			}
		}
	}

	// 进度条
	.progress-bar {
		margin-top: 24rpx;

		.progress-info {
			display: flex;
			justify-content: space-between;
			font-size: 24rpx;
			color: #999;
			margin-bottom: 12rpx;
		}

		.progress-track {
			height: 12rpx;
			background-color: #f5f5f5;
			border-radius: 6rpx;
			overflow: hidden;
		}

		.progress-fill {
			height: 100%;
			background: linear-gradient(90deg, #9c27b0, #ba68c8);
			border-radius: 6rpx;
			transition: width 0.3s ease;
		}
	}
}

// 规则弹窗
.rules-popup {
	background-color: #fff;
	border-radius: 24rpx 24rpx 0 0;
	overflow: hidden;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 2rpx solid #f0f0f0;

		.title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}
	}

	.popup-content {
		height: 600rpx;
		padding: 32rpx;
	}

	.rule-section {
		margin-bottom: 40rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.rule-title {
			font-size: 30rpx;
			font-weight: 600;
			color: #333;
			margin-bottom: 20rpx;
		}

		.rule-list {
			.rule-item {
				display: flex;
				gap: 16rpx;
				margin-bottom: 16rpx;

				.num {
					flex-shrink: 0;
					width: 40rpx;
					height: 40rpx;
					background: linear-gradient(135deg, #9c27b0, #ba68c8);
					color: #fff;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					font-weight: 600;
				}

				.text {
					flex: 1;
					font-size: 26rpx;
					color: #666;
					line-height: 1.6;
				}
			}
		}
	}
}
</style>